import { SupabaseClient } from '@supabase/supabase-js'

import { MessageRoleEnum, MessageStatusEnum } from '@/configs/enums'

class MessageController {
  private supabase: SupabaseClient

  constructor(supabase: SupabaseClient) {
    this.supabase = supabase
  }

  async createUserMessage(threadId: string, text: string) {
    console.log('createMessage', threadId, text)

    const { data, error } = await this.supabase.from('messages').insert({
      content: text,
      thread_id: threadId,
      role: MessageRoleEnum.USER,
      status: MessageStatusEnum.DONE,
    })

    if (error) {
      throw new Error(error.message)
    }
  }

  async createAssistantMessage(threadId: string) {
    const { data, error } = await this.supabase
      .from('messages')
      .insert({
        content: '',
        thread_id: threadId,
        role: MessageRoleEnum.ASSISTANT,
        status: MessageStatusEnum.GENERATING,
      })
      .select('*')
      .single()
    if (error) {
      throw new Error(error.message)
    }

    return data.id
  }

  async updateMessage(messageId: string, update: any) {
    const { data, error } = await this.supabase
      .from('messages')
      .update(update)
      .eq('id', messageId)

    if (error) {
      throw new Error(error.message)
    }
  }
}

export default MessageController
